<template>
    <div class="login-panel">
        <n-card title="管理后台登录">
            <n-form :rules = "rules" :model = "admin">
               <n-form-item path="account" label = "账号">
                  <n-input v-model:value="admin.account" placeholder = "请输入账号"/>
               </n-form-item>
               <n-form-item path = "password" label = "密码">
                  <n-input v-model:value = "admin.password" type="password" placeholder="请输入密码"/>
               </n-form-item>
            </n-form>
            <template #footer>
               <n-checkbox v-model:checked = "admin.rember" label = "记住我"/>
               <n-button @click="login">登录</n-button> 
            </template>
        </n-card>
    </div>
</template>

<script setup>

    import { ref,reactive,inject } from 'vue';
    import { AdminStore } from '../stores/AdminStore'

    // 引入路由模块
    import { useRouter, useRoute } from 'vue-router'
    const router =  useRouter()
    const route = useRoute()

 
    // 信息标签实例化
    const message = inject("message")
    const axios = inject("axios")
    const adminStore = AdminStore()



    /**验证表单规则 */
    let rules = {
        account:[
            {required:true,message:"请输入账号",trigger:"blue"},
            {min:3,max:12,message:"账号长度在3到12个字符",trigger:"blur"},
        ],
        password:[
            {required:true,message:"请输入密码",trigger:"blue"},
            {min:6,max:18,message:"密码长度在6到18个字符",trigger:"blur"},  
        ]
    };

    const admin = reactive({
        // 初始化用户信息，以及记住我信息录入 ,如果记住我信息读不到，默认为空
        account: localStorage.getItem("account") || "",
        password: localStorage.getItem("password") ||"",
        rember: localStorage.getItem("rember") == 1 || false
    })

    const login = async ()=>{

        // 利用axios模块对后台的登录接口进行延时访问，
        let result = await axios.post("/admin/login",{
            account:admin.account,
            password:admin.password
        });

        // 如果结果内 data 对象内的 code 节点状态为200 表示登录成功
        if(result.data.code == 200){
            // 存储登录数据
            adminStore.token = result.data.data.token
            adminStore.account = result.data.data.account
            adminStore.id = result.data.data.id

            // 记住我功能开发
            if(admin.rember){
                localStorage.setItem("account",admin.account)
                localStorage.setItem("password",admin.password)
                localStorage.setItem("rember",admin.rember? 1 : 0)               
            }

            //通过路由对页面进行跳转
            router.push("/dashboard")
            // 登录成功消息提示
            message.success("登录成功")
        }
        else{
            message.error("登录失败")
        }

    }
    

</script>

<style lang="scss" scoped>
.login-panel{
    width: 500px;
    margin: 0 auto;
    margin-top: 130px;
}

</style>